package net.NingXiaRuiTai.ShortChain.component;

import lombok.extern.slf4j.Slf4j;
import net.NingXiaRuiTai.ShortChain.config.ShardingDBConfig;
import net.NingXiaRuiTai.ShortChain.config.ShardingTableConfig;
import net.NingXiaRuiTai.ShortChain.utils.CommonUtil;
import org.springframework.stereotype.Component;

/**
 * 生成短链码
 */
@Component
@Slf4j
public class ShortLinkComponent {
    private static final String CHARS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public String createShortLink(String param) {
        long l = CommonUtil.murmurHash(param);
        String code = encodeToBase62(l);
        code= ShardingDBConfig.getRandomDBPrefix(code)+code+ ShardingTableConfig.getRandomTableSuffix(code);

        return code;
    }
    /**
     * 10进制转62进制
     *
     * @param num 10进制数
     * @return 62进制数
     */
    private String encodeToBase62(long num) {
        StringBuffer sb = new StringBuffer();
        do {
            int i = (int) (num % 62);
            sb.append(CHARS.charAt(i));
            num /= 62;
        } while (num > 0);
        return sb.reverse().toString();
    }


}




